package chaoyue.study.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AsyncService implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    public void doSome() {
        log.info("start doSome...");
        doSomeLong(); // 直接这样调用会失效，因为代理不起作用（与事务的处理方式一样）
        AsyncService currentProxy = applicationContext.getBean(AsyncService.class);
        currentProxy.doSomeLong();// 获取代理对象后进行异步方法调用
        log.info("end doSome...");
    }

    @Async
    public void doSomeLong() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("task finished..." + Thread.currentThread().getName());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
